package com.csj.DesignPattern.proxy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory {

    private TrainStation trainStation = new TrainStation();

    //Cglib中的代理类属于目标类的字类,所以不能对final类进行代理
    public TrainStation getProxyInstance() {
        //类似于JDK的Proxy类，用来生成代理类的
        Enhancer enhancer = new Enhancer();
        //设置代理类的父类的字节码对象
        enhancer.setSuperclass(TrainStation.class);
        //设置回调函数
        enhancer.setCallback(
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        System.out.println("代售点收取费用(Cglib代理)");
                        Object invoke = method.invoke(trainStation, objects);
                        return invoke;
                    }
                }
        );
        //创建代理对象
        TrainStation proxyInstance = (TrainStation) enhancer.create();
        return proxyInstance;
    }
}
